package com.yangrui.app.service.impl;

import com.yangrui.app.entity.User;
import com.yangrui.app.mapper.UserMapper;
import com.yangrui.app.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

import static com.yangrui.app.util.Md5Util.*;
import static com.yangrui.app.util.NullUtil.*;
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public int register(User user) {
        if(isBlank(user.getUsername()) || isBlank(user.getPassword()) || isBlank(user.getPhone())){
            return -1;
        }
        if (isBlank(user.getRealName())) {
            user.setRealName(UUID.randomUUID().toString().replace("-", ""));
        }
        if(isBlank(user.getAvatar())){
            user.setAvatar("default-avatar.jpg");
        }
        user.setPassword(encrypt(user.getPassword()));
        return userMapper.insert(user);

    }

    @Override
    public User login(String username, String password) {
        User user = userMapper.selectByUsername(username);

        if (isNull(user)){
            return new User(-1,"账号不存在",null,null,null,null,null,null);
        }
        if(!user.getPassword().equals(encrypt(password))){
            return new User(-2,"密码错误",null,null,null,null,null,null);
        }
        return user;
    }

    @Override
    public User selectById(int id) {
        User user = userMapper.selectById(id);
        if (isNull(user)){
            return new User(0,"用户不存在",null,null,null,null,null,null);
        }
        return user;
    }
}

